package org.mparts.client.ui;

import java.util.List;

import org.mparts.client.content.Images;
import org.mparts.client.content.Strings;
import org.mparts.client.place.MainPlace;
import org.mparts.client.ui.INewsView.INewsPresenter.ACTIONS;
import org.mparts.shared.proxy.NewsProxy;
import org.mparts.shared.proxy.PartitemProxy;
import org.mparts.shared.request.MpartsRequest;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.SafeHtmlCell;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ResizeComposite;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.sencha.gxt.cell.core.client.SimpleSafeHtmlCell;
import com.sencha.gxt.core.client.IdentityValueProvider;
import com.sencha.gxt.core.client.XTemplates;
import com.sencha.gxt.core.client.XTemplates.XTemplate;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.loader.ListLoadConfig;
import com.sencha.gxt.data.shared.loader.ListLoadResult;
import com.sencha.gxt.data.shared.loader.ListLoader;
import com.sencha.gxt.data.shared.loader.LoadResultListStoreBinding;
import com.sencha.gxt.data.shared.loader.RequestFactoryProxy;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.Dialog;
import com.sencha.gxt.widget.core.client.ListView;
import com.sencha.gxt.widget.core.client.Dialog.PredefinedButton;
import com.sencha.gxt.widget.core.client.ListViewCustomAppearance;
import com.sencha.gxt.widget.core.client.box.AlertMessageBox;
import com.sencha.gxt.widget.core.client.box.ConfirmMessageBox;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.event.HideEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.HideEvent.HideHandler;
import com.sencha.gxt.widget.core.client.info.Info;
import com.sencha.gxt.widget.core.client.toolbar.ToolBar;

public class NewsView extends ResizeComposite implements INewsView {

	public interface NewsRenderer extends XTemplates {
		@XTemplate("<p class='{style.newsTitle}'><b>{data.newsDate:date(\"dd.MM.yyyy\")}</b></p>")
		public SafeHtml render(NewsProxy data, NewsStyle style);
	}

	interface Bundle extends ClientBundle {
		@Source("NewsList.css")
		NewsStyle css();
	}

	interface NewsStyle extends CssResource {
		String newsItem();
		String newsTitle();
		String even();
	}
		  
	public interface Binder extends UiBinder<Widget, NewsView> {
	}

	private static final NewsProxyProperties newsProps = GWT
			.create(NewsProxyProperties.class);

	private NewsRenderer renderer;

	private INewsPresenter presenter;

	@UiField
	ContentPanel cont;

	@UiField
	VerticalLayoutContainer vCont;
	
	@UiField
	ToolBar toolBar;
	
	Strings strings;

	ListStore<NewsProxy> store = new ListStore<NewsProxy>(newsProps.key());

	@UiField(provided = true)
//	ListView<NewsProxy, String> listView = new ListView<NewsProxy, String>(
//			store, newsProps.content()) {
//		@Override
//		protected void onAfterFirstAttach() {
//			super.onAfterFirstAttach();
//			Scheduler.get().scheduleDeferred(new ScheduledCommand() {
//				@Override
//				public void execute() {
//					Log.debug("load news list...");
//					loader.load();
//				}
//			});
//		}
//	};
	ListView<NewsProxy, NewsProxy> listView = new ListView<NewsProxy, NewsProxy>(
			store, new IdentityValueProvider<NewsProxy>() {

				@Override
				public void setValue(NewsProxy object, NewsProxy value) {

				}
			}) {

		@Override
		protected void onAfterFirstAttach() {
			super.onAfterFirstAttach();
			Scheduler.get().scheduleDeferred(new ScheduledCommand() {
				@Override
				public void execute() {
					Log.debug("load news list...");
					loader.load();
				}
			});
		}

	};

	private RequestFactoryProxy<ListLoadConfig, ListLoadResult<NewsProxy>> proxy;

	private ListLoader<ListLoadConfig, ListLoadResult<NewsProxy>> loader;

	private Bundle b;
	
	class NewsCell extends AbstractCell<NewsProxy> {

		@Override
		public void render(com.google.gwt.cell.client.Cell.Context context,
				NewsProxy value, SafeHtmlBuilder sb) {
			if (value == null) {
				return;
			}
			Log.debug("news: " + store.indexOf(value));
			int even = store.indexOf(value) % 2;
			sb.appendHtmlConstant("<div class='" + b.css().newsItem() + ( even == 1 ? " " + b.css().even() : "" ) + "'>");
			sb.append(renderer.render(value, b.css()));
			sb.appendHtmlConstant(value.getContent() + "</div>");			
		}
		
	}

	@Inject
	public NewsView(Images images, Strings strings, Binder uiBinder,
			NewsRenderer renderer, Bundle bundle) {
		this.strings = strings;
		this.renderer = renderer;
		cont = (ContentPanel) uiBinder.createAndBindUi(this);
		//initWidget(cont);
		b = bundle;
		b.css().ensureInjected();
		
		listView.setCell(new NewsCell());
		listView.getElement().getStyle().setProperty("borderBottom", "none");

//	  		listView.setCell(new SimpleSafeHtmlCell<NewsProxy>(
//					new AbstractSafeHtmlRenderer<NewsProxy>() {
//
//						@Override
//						public SafeHtml render(NewsProxy object) {
//							return NewsView.this.renderer.render(object, b.css());
//						}
//					}));
//		      ListViewCustomAppearance<NewsProxy> appearance = new ListViewCustomAppearance<NewsProxy>(b.css().newsItem()) {
//		            @Override
//		            public void renderEnd(SafeHtmlBuilder builder) {
////		              String markup = new StringBuilder("<div class=\"").append(CommonStyles.get().clear()).append("\"></div>").toString();
////		              builder.appendHtmlConstant(markup);
//		            }
//		     
//		            @Override
//		            public void renderItem(SafeHtmlBuilder builder, SafeHtml content) {
//		              builder.appendHtmlConstant("<div class='" + b.css().newsItem() + "'>");
//		              builder.append(content);
//		              builder.appendHtmlConstant("</div>");
//		            }
//		     
//		          };
	}

	protected void createLoader() {
		loader = new ListLoader<ListLoadConfig, ListLoadResult<NewsProxy>>(
				proxy);
		loader.addLoadHandler(new LoadResultListStoreBinding<ListLoadConfig, NewsProxy, ListLoadResult<NewsProxy>>(
				store));
	}

	// protected void createProxy() {
	// proxy = new RequestFactoryProxy<ListLoadConfig,
	// ListLoadResult<PartitemProxy>>() {
	// @Override
	// public void load(ListLoadConfig loadConfig, Receiver<? super
	// ListLoadResult<PartitemProxy>> receiver) {
	// MpartsRequest req = rf.mpartsRequest();
	// req.partitemList().to(receiver);
	// // List<SortInfo> sortInfo = createRequestSortInfo(req,
	// loadConfig.getSortInfo());
	// // List<FilterConfig> filterConfig = createRequestFilterConfig(req,
	// loadConfig.getFilters());
	// // req.getPosts(loadConfig.getOffset(), loadConfig.getLimit(), sortInfo,
	// filterConfig).to(receiver);
	//
	// req.fire();
	// }
	// };
	// }

	@Override
	public void setPresenter(INewsPresenter presenter) {
		this.presenter = presenter;
	}

	@Override
	public ListStore<NewsProxy> getStore() {
		return store;
	}

	@Override
	public void loadStore() {
		loader.load();
	}

	@Override
	public void setProxy(
			RequestFactoryProxy<ListLoadConfig, ListLoadResult<NewsProxy>> proxy) {
		this.proxy = proxy;
		createLoader();
	}
	
	@UiHandler("addButton")
	public void onAdd(SelectEvent event) {
		presenter.actionNews(null, ACTIONS.ADD);
	}
	
	@UiHandler("editButton")
	public void onEdit(SelectEvent event) {
		if (listView.getSelectionModel().getSelectedItem() != null) {
			presenter.actionNews(listView.getSelectionModel().getSelectedItem(), ACTIONS.EDIT);
		} else {
			AlertMessageBox d = new AlertMessageBox(strings.alertTitle(), strings.emptyNewsAlert());
			d.show();
		}
	}
	
	@UiHandler("deleteButton")
	public void onDelete(SelectEvent event) {
		if (listView.getSelectionModel().getSelectedItem() != null) {
			final ConfirmMessageBox box = new ConfirmMessageBox(
					strings.confirm(), strings.confirmDeleteNews());
			box.addHideHandler(new HideHandler() {

				@Override
				public void onHide(HideEvent event) {
					Dialog btn = (Dialog) event.getSource();
					Log.debug("Button '{0}' pressed", btn
							.getHideButton().getText());
					if (box.getHideButton() == box
							.getButtonById(PredefinedButton.YES
									.name())) {
						presenter.actionNews(listView.getSelectionModel().getSelectedItem(), ACTIONS.DELETE);
					}
				}
			});
			box.show();
		} else {
			AlertMessageBox d = new AlertMessageBox(strings.alertTitle(), strings.emptyNewsAlert());
			d.show();
		}
	}

	@Override
	public void showToolBar(boolean show) {
		toolBar.setVisible(show);		
	}

	@Override
	public Widget asWidget() {
		return cont;
	}
	
	
}
